﻿using Chat.Common;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public class MemberSettingPanel : MonoBehaviour
{
    /// <summary>
    /// 父对象位置
    /// </summary>
    public Transform MemberParent;
    /// <summary>
    /// 要生成的成员预制体
    /// </summary>
    public GameObject MemberPrefab;
    /// <summary>
    /// 客户进入队列
    /// </summary>
    private Queue<string> enterClients = new Queue<string>();
    /// <summary>
    /// 客户退出队列
    /// </summary>
    private Queue<string> exitClients = new Queue<string>();

    private void Awake()
    {
        Singleton<TcpServer>.GetInstance().OnClientEnter += OnMemberEnter;
        Singleton<TcpServer>.GetInstance().OnClientExit += OnMemberExit;
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //Debug.Log($"客户进入队列:{enterClients.Count}\t客户退出队列:{exitClients.Count}");
        // 客户进入队列不为空
        if(enterClients.Count != 0)
        {
            string curClient = enterClients.Dequeue();
            GameObject go = Instantiate(MemberPrefab) as GameObject;
            go.transform.SetParent(MemberParent);
            go.GetComponent<Member>().BaseClient = Singleton<ClientManager>.GetInstance().GetValue(curClient);
            Singleton<MemberManager>.GetInstance().Add(go.GetComponent<Member>());

            //CtlMsgHandle.GetMemList(); // 有成员进入聊天室
            Member param = go.GetComponent<Member>();
            Singleton<CommandSender>.GetInstance().SendControlCmd(ControlType.EnterServer, null, param.ToString());
        }
        // 客户退出队列不为空
        if(exitClients.Count != 0)
        {
            string curClient = exitClients.Dequeue();

            //Member param = Singleton<MemberManager>.GetInstance().GetMember(curClient);
            //Singleton<CommandSender>.GetInstance().SendControlCmd(ControlType.ExitServer,null,param.ToString());

            Singleton<MemberManager>.GetInstance().GetValue(curClient).DestroySelf();
            Singleton<MemberManager>.GetInstance().Remove(curClient);

            //CtlMsgHandle.GetMemList();  // 有成员退出聊天室

        }
    }
    void OnMemberEnter(string clientId)
    {
        Debug.Log($"客户{clientId}进入");
        enterClients.Enqueue(clientId);
    }
    void OnMemberExit(string clientId)
    {
        Debug.Log($"客户{clientId}退出");
        exitClients.Enqueue(clientId);
    }
}